package drds.configuration.db.xml_mapping.dynamic_tag.tag_handler;

//import tool.plus.db.xml_mapping.dynamic_tag.sql_template.XmlMapperBuilder;

import drds.configuration.db.xml_mapping.dynamic_tag.sql_template.XmlMapperBuilder;
import drds.configuration.db.xml_mapping.dynamic_tag.tag.ChooseTag;
import drds.configuration.db.xml_mapping.dynamic_tag.tag.Tag;
import drds.configuration.db.xml_mapping.dynamic_tag.xml_node.XmlNode;

import java.util.ArrayList;
import java.util.List;

public class ChooseTagHandler implements TagHandler {
    private XmlMapperBuilder xmlMapperBuilder;

    public ChooseTagHandler(XmlMapperBuilder xmlMapperBuilder) {
        this.xmlMapperBuilder = xmlMapperBuilder;
    }

    @Override
    public void handleNode(XmlNode xmlNodeToHandle, List<Tag> tagList) {
        List<Tag> whenTagList = new ArrayList<>();
        List<Tag> otherwiseTagList = new ArrayList<>();
        //
        handleWhenOtherwiseTagList(xmlNodeToHandle, whenTagList, otherwiseTagList);
        Tag otherwiseTag = getDefaultTag(otherwiseTagList);
        ChooseTag chooseTag = new ChooseTag(whenTagList, otherwiseTag);
        tagList.add(chooseTag);
    }

    private void handleWhenOtherwiseTagList(XmlNode chooseXmlNode, List<Tag> whenTagList, List<Tag> otherwiseTagList) {
        List<XmlNode> childrenXmlNodeList = chooseXmlNode.getChildrenXmlNodeList();
        for (XmlNode childXmlNode : childrenXmlNodeList) {
            String tagName = childXmlNode.getNode().getNodeName();
            TagHandler tagHandler = xmlMapperBuilder.tagNameToXmlNodeHandlerMap.get(tagName);
            //
            if (tagHandler instanceof IfTagHandler) {
                tagHandler.handleNode(childXmlNode, whenTagList);
            } else if (tagHandler instanceof OtherwiseTagHandler) {
                tagHandler.handleNode(childXmlNode, otherwiseTagList);
            }
        }
    }

    /**
     * list取其中一个
     */
    private Tag getDefaultTag(List<Tag> otherwiseTags) {
        Tag defaultTag = null;
        if (otherwiseTags.size() == 1) {
            defaultTag = otherwiseTags.get(0);
        } else if (otherwiseTags.size() > 1) {
            throw new RuntimeException("Too many default (otherwise) elements in choose statement_handler.");
        }
        return defaultTag;
    }
}
